/**
 * 关闭当前页（或所有页），将当前页面参数和路径带到登录页，登录后再跳转到该页面
 * 当要求当前页必须登录时，就用这个方法跳转到密码登录页
 * 默认自动获取当前页面的路径和参数
 * query:Object 跳转到指定页面需要的参数,ru: {userId:1,userName:'li'}
 * path:指定页面的路径   要以绝对路径开头,不传或传null就默认使用当前路径
 * close:是否关闭所有页面跳转
 */
function getParamsLogin (close = false, path, query = {}) {
  let returnPage = {}
  if (path) {
    returnPage = {
      path: path,
      query: query
    }
  } else {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1]; //当前页面
    let currentPath = '/' + currentPage.route
    let currentQuery = currentPage.options || {}
    returnPage = {
      path: currentPath,
      query: currentQuery
    }
  }
  returnPage = JSON.stringify(returnPage)
  let str = `/package/system/login?returnPage=${returnPage}`

  if (close) {
    uni.reLaunch({
      url: str,
    })
  } else {
    uni.redirectTo({
      url: str,
      fail: () => {
        uni.reLaunch({
          url: str,
        })
      }
    })
  }
}

/**
 * 根据参数构建URL；
 */
function buildUrl(uri, params) {
  let tmpParams = [];

  Object.keys(params).forEach((key) => {

    let value = params[key]
    if (typeof value === 'undefined' || value === null) {
      value = '';
    }
    tmpParams.push([key, value].join('='));
  });
  let str = ''
  if (tmpParams && tmpParams[0]) {
    str = '?' + tmpParams.join('&')
  }
  return uri + str
}

module.exports = {
  getParamsLogin,
  buildUrl
}